package com.twh.www.controller;

import com.twh.www.entity.*;
import com.twh.www.service.WnAddressService;
import com.twh.www.service.WnOrderService;
import com.twh.www.service.WnCartService;
import com.twh.www.service.WnGoodsService;
import com.twh.www.service.WnOrderItemService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping
public class OrderController {

    @Autowired
    private WnOrderService orderService;
    @Autowired
    private WnCartService cartService;
    @Autowired
    private WnGoodsService goodsService;
    @Autowired
    private WnAddressService addressService;
    @Autowired
    private WnOrderItemService orderItemService;

    // 创建订单
    @PostMapping("/order/submit")
    public String submitOrder(@RequestParam Integer addressId,
                              @RequestParam String payType,
                              HttpSession session,
                              Model model) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) return "redirect:/login";

        List<WnCart> cartList = cartService.getCartByUserId(user.getId());
        if (cartList.isEmpty()) {
            model.addAttribute("msg", "购物车为空");
            return "order_add";
        }

        // 查询收货地址
        WnAddress address = addressService.getById(addressId);
        if (address == null) {
            model.addAttribute("msg", "请选择收货地址");
            return "order_add";
        }

        // 校验库存
        for (WnCart cart : cartList) {
            WnGoods goods = goodsService.getById(cart.getGoodsId());
            if (goods == null || goods.getStock() < cart.getNum()) {
                model.addAttribute("msg", goods.getName() + "库存不足");
                return "order_add";
            }
        }

        // 生成订单号
        String orderNo = UUID.randomUUID().toString().replace("-", "").substring(0, 16);

        // 计算总价
        BigDecimal total = cartList.stream()
                .map(item -> item.getGoodsPrice().multiply(BigDecimal.valueOf(item.getNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 创建订单
        WnOrder order = new WnOrder();
        order.setNo(orderNo);
        order.setAddTime(LocalDateTime.now());
        order.setUserId(user.getId());
        order.setTotalMoney(total);
        order.setStatus("1");
        // 设置收货信息
        order.setAddress(address.getProvince() + address.getCity() + address.getArea() + address.getStreet());
        order.setAccept(address.getAccept());
        order.setTelphone(address.getTelphone());
        order.setPayType(payType);

        // 保存订单
        orderService.save(order);

        // 保存订单明细
        for (WnCart cart : cartList) {
            WnOrderItem item = new WnOrderItem();
            item.setOrderId(order.getId());
            item.setGoodsId(cart.getGoodsId());
            item.setName(cart.getGoodsName());
            item.setImage(cart.getGoodsImage());
            item.setPrice(cart.getGoodsPrice());
            item.setNum(cart.getNum());
            orderItemService.save(item);
        }

        // 扣减库存
        for (WnCart cart : cartList) {
            WnGoods goods = goodsService.getById(cart.getGoodsId());
            goods.setStock(goods.getStock() - cart.getNum());
            goodsService.updateById(goods);
        }



        // 跳转到订单成功页面
        model.addAttribute("OrderNo", orderNo);
        model.addAttribute("totalPrice", total);
        model.addAttribute("payType", payType);
        return "order_submit";
    }

    // 查询订单列表
    @GetMapping("/order/list")
    public String listOrders(@RequestParam(required = false) String no,
                             HttpSession session,
                             Model model) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) return "redirect:/login";
        // 只查当前用户的订单
        List<WnOrder> orders = orderService.lambdaQuery()
                .eq(WnOrder::getUserId, user.getId())
                .like(no != null && !no.isEmpty(), WnOrder::getNo, no)
                .ne(WnOrder::getStatus, "5")
                .list();
        for (WnOrder order : orders) {
            List<WnOrderItem> items = orderItemService.lambdaQuery().eq(WnOrderItem::getOrderId, order.getId()).list();
            order.setItems(items);
        }
        model.addAttribute("orders", orders);
        return "orders";
    }

//    // 修改订单收货信息
//    @PostMapping("/order/updateAddress")
//    @ResponseBody
//    public String updateOrderAddress(@RequestParam Integer orderId,
//                                     @RequestParam String address,
//                                     @RequestParam String accept,
//                                     @RequestParam String telphone) {
//        WnOrder order = orderService.getById(orderId);
//        if (order == null || !"待支付".equals(order.getStatus())) {
//            return "fail";
//        }
//        order.setAddress(address);
//        order.setAccept(accept);
//        order.setTelphone(telphone);
//        orderService.updateById(order);
//        return "success";
//    }

    // 逻辑删除订单
    @PostMapping("/order/delete")
    @ResponseBody
    public String deleteOrder(@RequestParam Integer orderId) {
        WnOrder order = orderService.getById(orderId);
        if (order == null) return "fail";
        order.setStatus("5");
        boolean result = orderService.updateById(order);
        System.out.println("orderId=" + orderId + ", 更新结果=" + result + ", 新状态=" + order.getStatus());
        return result ? "success" : "fail";
    }

    // 跳转到填写订单信息页面
    @GetMapping("/order/add")
    public String addOrderPage(HttpSession session, Model model) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) return "redirect:/login";
        // 查询购物车商品
        List<WnCart> carItems = cartService.getCartByUserId(user.getId());
        model.addAttribute("carItems", carItems);
        // 查询用户地址列表
        List<WnAddress> addresses = addressService.getByUserId(user.getId());
        model.addAttribute("addresses", addresses);
        // 计算总金额
        BigDecimal totalPrice = carItems.stream()
                .map(item -> item.getGoodsPrice().multiply(BigDecimal.valueOf(item.getNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        model.addAttribute("totalPrice", totalPrice);
        return "order_add";
    }
    @PostMapping("/order/pay/now")
    @ResponseBody
    public String payOrder(String orderId,HttpSession session) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null || "".equals(orderId)) {
            return "login";
        }
        Integer userId = user.getId();
        return orderService.payOrder(userId, orderId,session);
    }
    //进入支付是否成功页面
    @GetMapping("/alipay/return")
    public String returnOrder(HttpSession session) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        String orderId = session.getAttribute("orderId").toString();
        if (user == null ) {
            return "login";
        }
        if(orderId == null || "".equals(orderId)) {
            return "redirect:/cart";
        }
        Integer userId = user.getId();
//        System.out.println("10: " + orderId + ", 10: " + userId);
        //模拟结算订单
        orderService.orderSuccess(orderId,userId);
//清空购物车
        cartService.removeByUserId(userId);
        return "pay_suc";
    }

}
